// Package internal
// Created by GoLand
// @User: lenora
// @Date: 2023/11/27
// @Time: 14:55

package main

import (
	"camp-homework/week02/internal/middlewares"
	"camp-homework/week02/internal/repository"
	"camp-homework/week02/internal/repository/dao"
	"camp-homework/week02/internal/service"
	"camp-homework/week02/internal/user"
	"github.com/gin-contrib/cors"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"strings"
	"time"
)

func main() {
	db := initDb()

	server := initWebServer()

	initUserHandler(db, server)
	_ = server.Run(":8081")
}

func initUserHandler(db *gorm.DB, server *gin.Engine) {
	ud := dao.NewUserDAO(db)
	ur := repository.NewUserRepository(ud)
	srv := service.NewUserService(ur)

	handler := user.NewUserHandler(srv)
	handler.RegisterRoutes(server)
}

func initDb() *gorm.DB {
	db, err := gorm.Open(mysql.Open("root:root@tcp(localhost:33052)/camp"))
	if err != nil {
		panic(err)
	}

	if err := initTables(db); err != nil {
		panic(err)
	}

	return db
}

func initWebServer() *gin.Engine {
	server := gin.Default()
	server.Use(cors.New(cors.Config{
		AllowCredentials: true,
		//AllowOrigins:     []string{"1.html", "2.html"},
		AllowHeaders: []string{"Content-Type"},
		AllowOriginFunc: func(origin string) bool {
			if strings.HasPrefix(origin, "http://localhost") {
				return true
			}
			return strings.Contains(origin, "localhost is mine")
		},
		MaxAge: 12 * time.Hour,
	}))

	//验证登录态中间件
	loginMiddleware := &middlewares.MiddlewareBuilder{}
	// TODO:session的使用方式
	// 存储数据的
	store := cookie.NewStore([]byte("key"))
	// 初始化session
	server.Use(sessions.Sessions("ssid", store), loginMiddleware.CheckLogin())

	return server
}

func initTables(db *gorm.DB) error {
	return db.AutoMigrate(&dao.User{})
}
